import React, {Component, Fragment} from 'react';
import * as routerRedux from "react-router-redux";
import {connect} from 'dva';
import {Dropdown,Menu,Pagination,Form, Card, Select, List, Tag, Icon, Avatar, Row,Col, Popconfirm, Input, Button, Divider, Table,DatePicker } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment/moment';
import styles from './List.less';
const FormItem = Form.Item;
export default @connect(({active, loading}) => ({
  active,
  loading: loading.models.list,
}))
@Form.create()
class ActiveList extends Component {
  state = {
    searchValues: {},
    pageData: {
      size: 10,
      page: 1
    },
    sortData: {
      order: "createTime",
      direction: "asc"
    }
  }
  componentDidMount() {
    this.fetchMore(this.state.pageData.page,this.state.pageData.size);
    const {dispatch} = this.props;
    /*@todo queryCount*/
    dispatch({
      type: 'active/queryCount',
    });
  }
  activeColumns = [
    {
      title: '序号Id',
      dataIndex: 'activityId',
      fixed: 'left',
      width: 100
    },
    {
      title: '活动标题',
      dataIndex: 'title',
      fixed: 'left',
      width: 300
    },
    {
      title: '状态',
      key:13,
      // dataIndex: 'status',
      fixed: 'left',
      dataIndex: "state",
      render: (text, item) => (
        <Fragment>
          <Dropdown overlay={<Menu>
            <Menu.Item key="UN_AUDIT"
                       onClick={() => this.changeStatus(item.activityId, 'END')}>END</Menu.Item>
            <Menu.Item key="NORMAL"
                       onClick={() => this.changeStatus(item.activityId, "NORMAL")}>NORMAL</Menu.Item>
            <Menu.Item key="AUDIT_NOT_PASS"
                       onClick={() => this.changeStatus(item.activityId, "OFF_LINE")}>OFF_LINE</Menu.Item>
          </Menu>} trigger={['click']}>
            <a className="ant-dropdown-link" href="#">
              <Icon type="edit"/>{item.state} <Icon type="down"/>
            </a>
          </Dropdown>
        </Fragment>
      ),
    },
    {
      title: '分类',
      // dataIndex: 'status',
      dataIndex: "categorys",
      key:1,
      render: val =>val&&val[0],
    },
    {
      title: '主讲人',
      key:2,
      // dataIndex: 'status',
      dataIndex: "speaker",
    },
    {
      title: '地点',
      key:3,
      // dataIndex: 'status',
      dataIndex: "address"
    },
    {
      title: '报名人数',
      // dataIndex: 'status',
      key:4,
      dataIndex: "attendCount",
      render: (text, item) => (
          <a onClick={() => this.gotoBookList(item.activityId)}>{item.attendCount}</a>
      ),
    },
    {
      title: '未支付成功数',
      key:5,
      // dataIndex: 'status',
      dataIndex: "state3",
    },
    {
      title: '阅读数',
      key:6,
      // dataIndex: 'status',
      dataIndex: "clickCount",
    },
    {
      title: '评论数',
      key:7,
      // dataIndex: 'status',
      dataIndex: "state5",
    },
    {
      title: '收藏数',
      key:8,
      // dataIndex: 'status',
      dataIndex: "state6",
    },
    {
      title: '喜欢数',
      key:9,
      // dataIndex: 'status',
      dataIndex: "favorCount",
    },
    {
      title: '创建时间',
      key:10,
      dataIndex: 'createTime',
      sorter: (a, b) => Date.parse(a.createTime) > Date.parse(b.createTime),
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '发布时间',
      key:11,
      dataIndex: 'state10',
      sorter: (a, b) => Date.parse(a.updateTime) > Date.parse(b.updateTime),
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: '类型type',
      key:12,
      // dataIndex: 'status',
      dataIndex: "type",
    },

    {
      title: '操作',
      width: 200,
      fixed: 'right',
      render: (text, item) => (
        <Fragment>
          <a onClick={() => this.articleEdit(item.activityId)}>修改</a>
          <Divider type="vertical"/>
          <Popconfirm onConfirm={() => this.articleDelete(item.activityId)} title="确定删除该类别吗？"
                      icon={<Icon type="question-circle-o" style={{color: 'red'}}/>}>
            <a><Icon type="delete" style={{marginRight: 8}}/>删除</a>
          </Popconfirm>
          <Divider type="vertical"/>
          <a onClick={() => this.gotoDetail(item.activityId)}>详情</a>

        </Fragment>
      ),
    },
  ];
  fetchMore = (page,size) => {
    const {dispatch} = this.props;
    const {pageData, searchValues, sortData} = this.state;
    dispatch({
      type: 'active/fetch',
      payload: {start: (page - 1) * 10, size: size, ...searchValues, ...sortData},
    });
  };
  /*编辑*/
  changeStatus = (id, status) => {
    this.props.dispatch({
      type: 'active/changeActiveState',
      payload: {
        id: id,
        state: status,
        searchValues: this.state.searchValues,
        sortData: this.state.sortData,
        pageData: {start: (this.state.pageData.page - 1) * 10, size: this.state.pageData.size}
      },
    })
  }
  /*详情*/
  gotoDetail = (id) => {
    this.props.dispatch(routerRedux.push({
      pathname: `/active/detail/${id}`,
    }))
  }
  /*报名列表*/
  gotoBookList=(id)=>{
    this.props.dispatch(routerRedux.push({
      pathname: `/active/book/${id}`,
    }))
  }
  /*删除*/
  articleDelete = (id) => {
    this.props.dispatch({
      type: 'active/delete',
      payload: {
        id: id,
        state: status,
        searchValues: this.state.searchValues,
        sortData: this.state.sortData,
        pageData: {start: (this.state.pageData.page - 1) * 10, size: this.state.pageData.size}
      },
    })
  }
  /*编辑*/
  articleEdit = (id) => {
    this.props.dispatch(routerRedux.push({
      pathname: `/active/edit/${id}`,
    }))
  }
  /*新增*/
  articleAdd = (id) => {
    this.props.dispatch(routerRedux.push({
      pathname: `/active/add`,
    }))
  }
  /*
  * 分页SizeChange
  * */
  onShowSizeChange = (current, pageSize) => {
    this.setState({
      pageData: {page:1,size:pageSize}
    })
    this.fetchMore(1,pageSize);
  }
  /*pageChange*/
  changePage = (page, pageSize) => {
    this.setState({
      pageData: {page:page,size:this.state.pageData.size}
    })
    this.fetchMore(page,this.state.pageData.size);
  }
  /*重置表单*/
  handleFormReset = () => {
    const {form, dispatch} = this.props;
    form.resetFields();
    this.setState({
      searchValues: {},
    });
    const {pageData, sortData} = this.state;
    dispatch({
      type: 'active/fetch',
      payload: {start: 0, size: pageData.size, ...sortData},
    });
    dispatch({
      type: 'active/queryCount',
    });
  };
  /*搜索*/
  handleSearch = e => {
    e.preventDefault();
    const {form} = this.props;
    function dealObjectValue(obj){
      var param = {};
      if ( obj === null || obj === undefined || obj === "" ) return param;
      for ( var key in obj ){
        if ( obj[key] !== null && obj[key] !== undefined && obj[key] !== "" ){
          param[key] = obj[key];
        }
      }
      return param;
    };
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        startCreateTime: fieldsValue.startCreateTime && moment(fieldsValue.startCreateTime).format("YYYY-MM-DD HH:mm:ss"),
        endCreateTime: fieldsValue.endCreateTime && moment(fieldsValue.endCreateTime).format("YYYY-MM-DD HH:mm:ss"),
      };
      this.setState({
        searchValues: dealObjectValue(values),
      });
      const {dispatch} = this.props;
      const {pageData, sortData} = this.state;
      dispatch({
        type: 'active/fetch',
        payload: {start: 0, size: pageData.size, ...dealObjectValue(values), ...sortData},
      });
      dispatch({
        type: 'active/queryCount',
        payload: {...dealObjectValue(values)}
      });
    });
  };
  render() {
    const {form, active: {list, countNum}, loading,} = this.props;
    const {pageData} = this.state;
    const {
      form: {getFieldDecorator},
    } = this.props;
    const mainSearch = (
      <Form layout="inline">
        <Row gutter={{md: 6, lg: 24, xl: 48}}>
          <Col md={6} sm={24}>
            <FormItem label="活动标题">
              {getFieldDecorator('title')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <Form.Item label="开始时间">
              {getFieldDecorator('startCreateTime')(
                <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: "200px"}} placeholder="请输入活动开始时间"/>
              )}
            </Form.Item>
          </Col>
          <Col md={6} sm={24}>
            <Form.Item label="结束时间">
              {getFieldDecorator('endCreateTime')(
                <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width: "200px"}} placeholder="请输入活动开始时间"/>
              )}
            </Form.Item>
          </Col>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button onClick={this.handleSearch} type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
    return (
      <PageHeaderWrapper
        title="活动列表"
        content={mainSearch}
      >
        <Card
          style={{marginTop: 24}}
          bordered={false}
          bodyStyle={{padding: '8px 32px 32px 32px'}}
        >
          <div className={styles.tableList}>
            <div className={styles.tableListOperator} style={{"marginBottom":"15px"}}>
              <Button icon="plus" type="primary" onClick={() => this.articleAdd()}>
                新建
              </Button>
            </div>
            <Table
              loading={loading}
              dataSource={list}
              scroll={{ x: 2000 }}
              pagination={false}
              columns={this.activeColumns}
              onChange={this.handleStandardTableChange}
            />
            <Pagination style={{"marginTop": "30px"}} showSizeChanger onChange={this.changePage}
                        onShowSizeChange={this.onShowSizeChange} defaultPageSize={pageData.size}
                        defaultCurrent={pageData.page} total={countNum}/>
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
